<template>
  <div class="building-container">
    <!-- //!搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input
        v-model="params.name"
        clearable
        placeholder="请输入内容"
        class="search-main"
        @clear="clearSearch"
      />
      <el-button type="primary" @click="getList">查询</el-button>
    </div>
    <!-- //!添加企业 -->
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/enterpriseAdd')">添加企业</el-button>
    </div>
    <!-- //!表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list" @expand-change="expandChange">
        <el-table-column type="expand">
          <template #default="scope">
            <el-table :data="scope.row.renderList">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status">
                <template #default="res">
                  {{ contractState(res.row.status) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="res">
                  <el-button size="mini" type="text" :disabled="res.row.status === 3" @click="outRent(res.row.id)">退租</el-button>
                  <el-button size="mini" type="text" :disabled="res.row.status === 1">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="mini" type="text" @click="addEnterprise(scope.row.id)">添加合同</el-button>
            <el-button size="mini" type="text">查看</el-button>
            <el-button size="mini" type="text" @click="editEnterprise(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="text" @click="romoveEnterprise(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- //!添加合同弹框 -->
    <el-dialog
      title="添加合同"
      :visible="rentDialogVisible"
      width="580px"
      @close="closeDialog"
      @open="openDialog"
    >
      <!-- 表单区域 -->
      <div class="form-container">
        <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option
                v-for="item in getRentBuildList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload
              ref="uploadRef"
              action="#"
              :http-request="upload"
            >
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <div slot="tip" class="el-upload__tip">支持扩展名：.doc .docx .pdf, 文件大小不超过5M</div>
            </el-upload>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="rentDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="formRentExpand">确 定</el-button>
        </span>

      </div>
    </el-dialog>
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        :page-size="params.pageSize"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>
<script>
import {
  getEnterpriseAPI,
  getRentListAPI,
  romoveEnterpriseAPI,
  getRentBuildListAPI,
  createRentAPI,
  upLoadBusinessAPI,
  outRentAPI } from '@/api/enterprise'
export default {
  data() {
    return {
      params: {
        pageSize: 10, // 每页条数
        page: 1, // 当前页数
        name: '' // 搜素的关键字
      },
      list: [],
      total: 0,
      rentDialogVisible: false, //! 控制弹框
      getRentBuildList: [], //! 楼宇数据
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      },
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件' }
        ]
      }
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    //! 渲染
    async getList() {
      const res = await getEnterpriseAPI(this.params)
      // console.log(res.data.rows)
      this.list = [...res.data.rows]
      this.total = res.data.total
      //! 将数据映射到列表数据里
      this.list = res.data.rows.map(item => {
        return {
          ...item,
          renderList: []
        }
      })
    },
    //! 清空叉号重新渲染接口
    clearSearch() {
      this.params.name = ''
      this.getList()
    },
    //! 分页
    handleCurrentChange(val) {
      this.params.page = val
      this.getList()
    },
    //! 编辑
    editEnterprise(id) {
      // console.log(id)
      this.$router.push({
        path: '/enterpriseAdd',
        query: { id }
      })
    },
    //! 删除
    romoveEnterprise(id) {
      this.$confirm('删除的数据不可恢复？', '删除操作', {
        distinguishCancelAndClose: true,
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      })
        .then(async() => {
          await romoveEnterpriseAPI(id)
          this.$message({
            type: 'success',
            message: '删除成功'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消删除'
          })
        })
    },
    //! 获取合同数据
    async expandChange(row, rows) {
      // console.log(row)
      const resquest = await getRentListAPI(row.id)
      // console.log(resquest.data)
      //! 将列表的数据赋值给映射的新数组
      // eslint-disable-next-line require-atomic-updates
      row.renderList = resquest.data
    },
    //! 修改状态
    contractState(state) {
      // console.log(state)
      const MAP = {
        0: '待生效',
        1: '生效中',
        2: '已到期',
        3: '已退租'
      }
      return MAP[state]
    },
    //! 修改弹框点击叉叉和空白状态 close(属性)
    //! 重置表单为空
    closeDialog() {
      this.rentDialogVisible = false
      this.rentForm = {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      }
      this.$refs.addForm.resetFields()
      this.$refs.uploadRef.clearFiles()
    },
    //! 打开楼宇列表
    async openDialog() {
      const res = await getRentBuildListAPI()
      // console.log(res)
      this.getRentBuildList = res.data
    },
    //! 上传合同
    async upload(res) {
      // console.log(res)
      // contract 租赁合同
      const formdata = new FormData()
      formdata.append('file', res.file)
      formdata.append('type', 'contract')
      const resquest = await upLoadBusinessAPI(formdata)
      // console.log(resquest.data)
      const { id, url } = resquest.data
      this.rentForm.contractId = id
      this.rentForm.contractUrl = url
      // 单独校验表单
      this.$refs.addForm.validate('contractId')
    },
    //! 提交表单
    formRentExpand() {
      this.$refs.addForm.validate(async valid => {
        // console.log(valid)
        if (valid) {
          const { buildingId, contractId, contractUrl, enterpriseId } = this.rentForm
          await createRentAPI({
            buildingId,
            contractId,
            contractUrl,
            enterpriseId,
            type: 0, // 合同类型
            // rentTime: [] // 合同时间
            startTime: this.rentForm.rentTime[0],
            endTime: this.rentForm.rentTime[1]
          })
          // console.log(res)
          this.rentDialogVisible = false
          this.getList()
        }
      })
    },
    //! 添加合同id
    addEnterprise(id) {
      this.rentDialogVisible = true
      this.rentForm.enterpriseId = id
    },
    //! 修改退租状态
    outRent(id) {
      this.$confirm('确认退租吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await outRentAPI(id)
        // 1. 调用接口
        // 2. 重新拉取列表
        this.getList()
        this.$message({
          type: 'success',
          message: '退租成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>exportToExcel

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container {
  margin: 10px 0px;
}
.page-container {
  padding: 4px 0px;
  text-align: right;
}
.form-container {
  padding: 0px 80px;
}
</style>
